<?php

namespace IDock\Insurance\AMIC\Request;

use IDock\IDock\IDock;
use IDock\IDock\IDockEnums;
use IDock\Insurance\AMIC\AMICEnums;
use IDock\Insurance\AMIC\Request\AllAMICRequest;
use IDock\Insurance\AMIC\Response\PremiumInquiryResponse;
use IDock\Printer\NonCar\NonCarSubCoveragePrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\Premium\PremiumRelationVisitor;

class PremiumInquiryRequest extends AllAMICRequest
{
    public $requestType = 'N0203';

    protected $response = PremiumInquiryResponse::class;

    protected $urlTip = '车险报价';

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public function generate(): array
    {
        $data = [
            'qtnBase' => $this->getMain(),
            'vehicle' => $this->carData(),
            'vehicleOwner' => $this->getOwnerData(),
        ];
        if($this->visitor->biStartData){
            $data['applicationBusi'] = $this->getBiData();
            $data['coverageItemList'] = $this->getCoverageList();
        }
        if($this->visitor->ciStartData){
            $data['applicationCI'] = $this->getCiData();
            $data['vehicleTaxation'] = $this->carShipTax();
        }
        if($this->visitor->getChargingPileVisitorList()){
            $data['chargingPostList'] = $this->chargingList();//todo
        }
        if($this->visitor->getNonCarInquiryVisitor()->getNonCarList()){
            $data['appliHealthInsList'] = ['appliHealthIns' => $this->getNonCarList()];
        }
        return $data;
    }

    private function getNonCarList()
    {
        $nonCarList = $this->visitor->getNonCarInquiryVisitor()->getNonCarList();
        $list = [];
        /**@var NonCarProductVisitor $value*/
        foreach ($nonCarList as $value){
            $tmp = [
                'prodNo' => '0760 ',
                'effectiveDate' => $this->visitor->ciStartData ?: $this->visitor->biStartData,
                'expireDate' => $this->visitor->ciEndData ?: $this->visitor->biEndData,
                'productCode' => $value->planCode,
                'appChannelDetailth' => $this->visitor->getExtInfoVisitor()->argc['appChannelDetailth'] ?? '',
                'agentCode' => $this->visitor->getExtInfoVisitor()->argc['appOperatorCode'] ?? '',
                'appAgreementNo' => $this->visitor->getExtInfoVisitor()->argc['appAgreementNo'] ?? '',
            ];
            $tmp['effectiveDate'] = date('YmdHi',strtotime($tmp['effectiveDate']));
            $tmp['expireDate'] = date('Ymd2400',strtotime($tmp['expireDate']));
            $list[] = $tmp;
        }
        return $list;
    }

    private function getBiData()
    {
        $arr = [
            'Isinstantflag' => intval($this->visitor->biEffectFlag),
            'effectiveDate' => date('YmdHi',strtotime($this->visitor->biStartData)),
        ];
        if($this->visitor->getExtInfoVisitor()->expectedDiscount){
            $arr['expectDiscount'] = $this->visitor->getExtInfoVisitor()->expectedDiscount;
        }
//        if($arr['Isinstantflag']){
//            if(date('i') <= 30){
//                $arr['effectiveDate'] = date('YmdHi',strtotime('+1 hour',strtotime($this->visitor->biStartData)));
//                if(date('H') + 1 == 24){
//                    $arr['effectiveDate'] = date('Ymd0000',strtotime('+1 day',strtotime($this->visitor->biStartData)));
//                }
//            }else{
//                $arr['effectiveDate'] = date('YmdHi',strtotime('+2 hours',strtotime($this->visitor->biStartData)));
//                if(date('H') + 2 == 24){
//                    $arr['effectiveDate'] = date('YmdH00',strtotime('+1 day',strtotime($this->visitor->biStartData)));
//                }elseif (date('H') + 2 > 24){
//                    $arr['effectiveDate'] = date('YmdH00',strtotime('+2 hours',strtotime($this->visitor->biStartData)));
//                }
//            }
//        }
        $arr['effectiveDate'] = date('YmdHi',strtotime($arr['effectiveDate']));
        $arr['expireDate'] = date('Ymd2400',strtotime('+1 year',strtotime($arr['effectiveDate'])));
        return $arr;
    }

    private function getCiData()
    {
        $arr = [
            'prodNo' => '0590',
            'Isinstantflag' => intval($this->visitor->ciEffectFlag),
            'effectiveDate' => date('YmdHi',strtotime($this->visitor->ciStartData)),
        ];
//        if($arr['Isinstantflag']){
//            if(date('i') <= 30){
//                $arr['effectiveDate'] = date('YmdHi',strtotime('+1 hour',strtotime($this->visitor->ciStartData)));
//                if(date('H') + 1 == 24){
//                    $arr['effectiveDate'] = date('Ymd0000',strtotime('+1 day',strtotime($this->visitor->ciStartData)));
//                }
//            }else{
//                $arr['effectiveDate'] = date('YmdHi',strtotime('+2 hours',strtotime($this->visitor->ciStartData)));
//                if(date('H') + 2 == 24){
//                    $arr['effectiveDate'] = date('YmdH00',strtotime('+1 day',strtotime($this->visitor->ciStartData)));
//                }elseif (date('H') + 2 > 24){
//                    $arr['effectiveDate'] = date('YmdH00',strtotime('+2 hours',strtotime($this->visitor->ciStartData)));
//                }
//            }
//        }
        $arr['effectiveDate'] = date('YmdHi',strtotime($arr['effectiveDate']));
        $arr['expireDate'] = date('YmdHi',strtotime('+1 year',strtotime($arr['effectiveDate'])));
        return $arr;
    }

    private function getMain()
    {
        $arr = [
            'appBusi' => intval((bool)$this->visitor->biStartData),
            'appCI' => intval((bool)$this->visitor->ciStartData),
            'appHealthIns' => $this->visitor->getNonCarInquiryVisitor()->getNonCarList() ? 1 : 0,
            'thirdPartyCode' => '',//接入点代码
            'insuredName' => $this->visitor->getInsuredVisitor()->name,
            'appOperatorCode' => $this->visitor->getExtInfoVisitor()->argc['appOperatorCode'] ?? '',//工号
            'appChannelDetailth' => $this->visitor->getExtInfoVisitor()->argc['appChannelDetailth'] ?? '',//三级渠道
            'employee' => '',
            'referraltrafficCode' => '',
            'sellingPerson' => '',
            'sellingOrg' => '',
            'sellingFlag' => '',
            'employeeID' => '',
            'employeeName' => '',
            'shareholderComCode' => '',
            'appAgreementNo' => $this->visitor->getExtInfoVisitor()->argc['appAgreementNo'] ?? '',
        ];
        if(!empty($this->visitor->getExtInfoVisitor()->argc['orderNo'])){
            $arr['orderNo'] = $this->visitor->getExtInfoVisitor()->argc['orderNo'];
        }
        return $arr;
    }

    private function getOwnerData()
    {
        $arr = [
            'vehicleOwnerName' => $this->visitor->getOwnerVisitor()->name,
            'vehicleOwnerType' => AMICEnums::$relationTypeCode[$this->visitor->getOwnerVisitor()->typeCode] ?? '',
            'vehicleOwnerIdentifyType' => AMICEnums::$certificateTypeCode[$this->visitor->getOwnerVisitor()->certificateTypeCode] ?? '',
            'vehicleOwnerIdentifyNumber' => $this->visitor->getOwnerVisitor()->certificateNo,
            'idCardStartDate' => $this->visitor->getOwnerVisitor()->certificateStartDate,
            'idCardEndDate' => $this->visitor->getOwnerVisitor()->certificateEndDate,
            'vehicleOwnerAddress' => $this->visitor->getOwnerVisitor()->address,
            'vehicleOwnerPhone' => $this->visitor->getOwnerVisitor()->mobile,
            'vehicleOwnerEmail' => $this->visitor->getOwnerVisitor()->email,
            'province' => $this->visitor->getOwnerVisitor()->provinceCode,
            'city' => $this->visitor->getOwnerVisitor()->cityCode,
            'area' => $this->visitor->getOwnerVisitor()->areaCode,
            'legalRep' => $this->visitor->getOwnerVisitor()->linkManName,
        ];
        if(empty($arr['vehicleOwnerIdentifyType'])){
            throw new \Exception("不支持该车主证件类型");
        }
        return $arr;
    }


    /**
     * 车辆信息
     * @return array
     */
    private function carData(): array
    {
        $data = [
            'vehicleId' => $this->visitor->getVehicleVisitor()->vehicleModelCode,
            'vehiclePrice' => $this->visitor->getVehicleVisitor()->vehiclePrice,
            'licensePlateNo' => $this->visitor->getVehicleVisitor()->licenseNo,
            'licensePlateType' => !empty($this->visitor->getVehicleVisitor()->licenseNo) ? (AMICEnums::$licenseTypeCode[$this->visitor->getVehicleVisitor()->licenseTypeCode] ?? '' ): '',//车辆种类
            'vehicleStyle' => $this->visitor->getVehicleVisitor()->vehicleStyleCode,//车辆类型代码
            'firstRegisterDate' => $this->visitor->getVehicleVisitor()->firstRegisterDate,
            'vin' => $this->visitor->getVehicleVisitor()->vin,
            'engineNo' => $this->visitor->getVehicleVisitor()->engineNo,
            'seatCount' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            'modelCode' => $this->visitor->getVehicleVisitor()->vehicleModelCode,
            'limitLoad' => round(floatval($this->visitor->getVehicleVisitor()->vehicleTonnage) / 1000,2),
            'wholeWeight' => round(floatval($this->visitor->getVehicleVisitor()->wholeWeight) / 1000,2),
            'displaceMent' => $this->visitor->getVehicleVisitor()->vehicleExhaust,
            'Power' => $this->visitor->getVehicleVisitor()->power,
            'transferDate' => $this->visitor->getVehicleVisitor()->transferDate,
            'noLicenseFlag' => intval((bool)$this->visitor->getVehicleVisitor()->licenseNo),//未上牌车辆标志
            'chgOwnerFlag' => intval($this->visitor->getVehicleVisitor()->isTransfer),//过户车辆标志
            'ecdemicVehicleFlag' => intval($this->visitor->getVehicleVisitor()->nonlocalCar),//外地车标志
            'fuelType' => AMICEnums::$energyType[$this->visitor->getVehicleVisitor()->energyTypeCode] ?? '',
            'useNature' => AMICEnums::$AMICCauseType[$this->visitor->getVehicleVisitor()->causeType] ?? '',
            'carFuelType' => AMICEnums::$fuelType[$this->visitor->getVehicleVisitor()->energyTypeCode] ?? '',
            'isLoan' => '0',//是否贷款车 默认 不是
            'carPriceType' => '1',//车辆价值确定方式：默认车辆实际价格
            'newCarSign' => intval($this->visitor->getVehicleVisitor()->isNewVehicle),
            'drivePermitDate' => $this->visitor->getVehicleVisitor()->issueDate,
            'specialCarFlag' => '0',//交强险过户车辆标志
            'vehiclePlatId' => $this->visitor->getExtInfoVisitor()->argc['vehiclePlatId'] ?? '',
        ];

        if ($this->visitor->getVehicleVisitor()->isCiTransfer) {
            $data['specialCarFlag'] = 1;
        }

        return $data;
    }

    /**
     * 险种信息
     * @return array
     */
    private function getCoverageList(): array
    {
        $list = [];
        $coverageList = $this->visitor->getCoverageVisitorList();
        $coverageList = array_combine(array_column($coverageList, 'coverageCode'), $coverageList);

        foreach ($coverageList as $coverage) {

            /*** @var PremiumCoverageVisitor $coverage */

            //交强险去除
            if ($coverage->coverageCode == 'C01001') {
                continue;
            }

            $one = [
                'coverageCode' => AMICEnums::$coverageCode[$coverage->coverageCode] ?? '',
                'sumLimit' => $coverage->amount,//保额
                'unit' => (string)intval($coverage->quantity),
                'unitAmount' => $coverage->unitAmount ?: $coverage->amount,
                'rate' => '',
                'glsType' => '',
                'repairFactoryType' => '',
                'unclaimAmount' => '',
                'deductibleRate' => '',
                'serverTime' => '',
            ];

            //乘客险
            if (in_array($coverage->coverageCode, ['C05001', 'C05002', 'C05003', 'C15001', 'C15002', 'C15003'])) {
                $one['unit'] = strval($this->visitor->getVehicleVisitor()->vehicleSeat - 1);
                $one['unitAmount'] = $coverage->unitAmount ?: $coverage->amount;
            }
            //绝对免赔率
            if (in_array($coverage->coverageCode, ['C02006', 'C03005', 'C04004','C05004','C12006', 'C13005', 'C14004', 'C15004'])) {
                $one['deductibleRate'] = $coverage->deductionRate;
            }
            //特约
            if(in_array($coverage->coverageCode,['C08001','C08002','C08003','C08004','C18001','C18002','C18003','C18004'])){
                $one['serverTime'] = $coverage->serviceTimes;
            }
            //修理期间
            if(in_array($coverage->coverageCode,['C03003','C13003','C03004','C13004']) ){
                $one['unitAmount'] = $coverage->amount;
            }
            //司机险
            if (in_array($coverage->coverageCode, ['C04001', 'C04002', 'C04003', 'C14001', 'C14002', 'C14003'])) {
                $one['unit'] = 1;
                $one['unitAmount'] = $coverage->amount;
            }
            //电网故障 车埙险
            if(in_array($coverage->coverageCode,['C02001','C12001','C16001'])){
                $one['sumLimit'] = $this->visitor->getExtInfoVisitor()->argc['actualPrice'] ?? '';
            }
            $list[] = $one;
        }
        return ['coverageItem' => $list];
    }

    /**
     * 充电桩
     * @return array
     */
    private function chargingList(): array
    {
        $list = [];
        foreach ($this->visitor->getChargingPileVisitorList() as $visitor) {
            /*** @var PremiumChargingPileVisitor $visitor */
            if(!empty($visitor->lossAmount)){
                $kindList = [
                    'coverageCode' => '0401203',
                    'chargingPostType' => $visitor->chargingPileType,
                    'chargingPostCode' => $visitor->chargingPileCode,
                    'chargingPostAddress' => $visitor->chargingPileAddress,
                    'chargingPostAddressType' => AMICEnums::$chargingPileAddressType[$visitor->chargingPileAddressType] ?? '',
                    'chargingPostKind' => AMICEnums::$chargingPileKind[$visitor->chargingPileKind] ?? '',
                    'chargingPostYearLimit' => AMICEnums::$chargingPileYearLimit[$visitor->chargingPileYearLimit] ?? '',
                    'amount' => $visitor->lossAmount,
                ];
                $list[] = $kindList;
            }
            if(!empty($visitor->liabilityAmount)){
                $kindList = [
                    'coverageCode' => '0401204',
                    'chargingPostType' => $visitor->chargingPileType,
                    'chargingPostCode' => $visitor->chargingPileCode,
                    'chargingPostAddress' => $visitor->chargingPileAddress,
                    'chargingPostAddressType' => AMICEnums::$chargingPileAddressType[$visitor->chargingPileAddressType] ?? '',
                    'chargingPostKind' => AMICEnums::$chargingPileKind[$visitor->chargingPileKind] ?? '',
                    'chargingPostYearLimit' => AMICEnums::$chargingPileYearLimit[$visitor->chargingPileYearLimit] ?? '',
                    'amount' => $visitor->liabilityAmount,
                ];
                $list[] = $kindList;
            }

        }
        return ['chargingPostData' => $list];

    }

    /**
     * 车船税
     * @return array
     */
    private function carShipTax(): array
    {
        $taxVisitor = $this->visitor->getCarTaxVisitor();

        $arr = [
            'taxpayerName' => $taxVisitor->taxpayerName,
            'taxpayerIdentifyNumber' => $taxVisitor->taxpayerCertificateNo,
            'taxConditionCode' => AMICEnums::$taxTypeCode[$taxVisitor->taxTypeCode] ?? '',//纳税类型
//            'payLastTime' => $taxVisitor->taxEndDate,
        ];
        if($arr['taxConditionCode'] == 'C'){
            $arr['taxDepartment'] = $taxVisitor->taxDepartment;
            $arr['taxPaymentRecptNo'] = $taxVisitor->taxDocumentNumber;
            $arr['deductionDueCode'] = AMICEnums::$taxReductionReasonCode[$taxVisitor->taxReductionReasonCode] ?? '';
            $arr['deductionDueType'] = $taxVisitor->taxReductionCode;
            if($taxVisitor->taxReductionCode == 'P'){
                $arr['deductionDueProportion'] = $taxVisitor->taxFreeRate;
            }else{
                $arr['Deduction'] = $taxVisitor->taxExemption;
            }
        }elseif ($arr['taxConditionCode'] == 'E' or $arr['taxConditionCode'] == 'P'){
            $arr['taxDepartment'] = $taxVisitor->taxDepartment;
            $arr['taxPaymentRecptNo'] = $taxVisitor->taxDocumentNumber;
            $arr['deductionDueCode'] = AMICEnums::$taxReductionReasonCode[$taxVisitor->taxReductionReasonCode] ?? '';
        }
        if(empty($arr['taxConditionCode'])){
            throw new \Exception("不支持该纳税类型");
        }
        return $arr;
    }

    /**
     * 通过身份证获取性别
     * @param $idcard
     * @return int
     * @throws \Exception
     */
    private function getGenderByIDcard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new \Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? '1' : '2';
    }
}
